package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/hashicorp/go-uuid"
	"net/http"
	"os"
	"perfect-admin/dao"
	"perfect-admin/global/response"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"perfect-admin/service"
	"strconv"
	"strings"
)

func GetFileList(c *gin.Context) {
	var queryInfo request.QueryInfo
	if err := c.ShouldBind(&queryInfo); err != nil {
		response.Response(c, 201, err.Error(), nil)
		return
	}
	files, total, err := service.GetFileList(queryInfo)
	if err != nil {
		response.Response(c, 202, err.Error(), nil)
	} else {
		response.Response(c, http.StatusOK, "获取file列表成功", map[string]interface{}{
			"files": files,
			"total": total,
		})
	}
	return
}

func UploadFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(203, gin.H{"msg": err, "file_path": nil})
		return
	}
	file_type_list := strings.Split(file.Filename, ".")
	var file_type string
	if len(file_type_list) > 0 {
		file_type = file_type_list[len(file_type_list)-1]
	}else {
		file_type = ""
	}
	uid, _ := uuid.GenerateUUID()
	filepath := "static/upload/files/" + uid + "." + file_type
	if err := c.SaveUploadedFile(file, filepath); err != nil {
		response.Response(c, 201, err.Error(), nil)
	}else{
		var size string
		if file.Size > 1000 {
			size = strconv.FormatInt(file.Size / 1000, 10) + "KB"
		}else {
			size = strconv.FormatInt(file.Size, 10) + "B"
		}
		dao.DB.Create(&model.SysFile{Path:"/"+ filepath,Name:file.Filename,Size:size, Type:file_type})
		response.Response(c, http.StatusOK, "上传成功", "/"+filepath)
	}
	return
}

func FileDownload(c *gin.Context)  {
	var file model.SysFile
	_ = c.ShouldBindJSON(&file)
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", file.Name +"." + file.Type))//fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	c.File(strings.Trim(file.Path, "/"))
}

func DeleteUploadFile(c *gin.Context) {
	var file model.SysFile
	err := c.ShouldBindJSON(&file)
	if err!=nil {
		response.Response(c, 201, "参数获取失败", nil)
	}
	file_path := strings.Trim(file.Path, "/")
	if err := os.Remove(file_path); err != nil {
		response.Response(c, 202, err.Error(), nil)
	}else{
		dao.DB.Unscoped().Delete(&file)
		response.Response(c, http.StatusOK, "删除成功", nil)
	}
	return
}

func UpdateFileName(c *gin.Context)  {
	var file request.FileRename
	if err := c.ShouldBindJSON(&file); err != nil {
		response.Response(c, 201, "获取参数失败", nil)
		return
	}
	if err := service.FileRename(file); err != nil{
		response.Response(c, 202, err.Error(), nil)
	}else {
		response.Response(c, http.StatusOK, "重命名成功", nil)
	}
	return

}